﻿using System;
using System.Collections.Generic;
using System.Text;
using EmbeddedSharp.Core;

namespace EmbeddedSharp.Scripting.Function.List
{

    /// <summary>
    /// lst = union([1,2], [2,3], [,5,7]);
    /// echo(lst);
    /// 
    /// the expected result is [1,2,3,5,7]
    /// </summary>
    public class UnionNode : FuncNode
    {

        public UnionNode()
            : base()
        {
            this.Value = "union";
        }

        public override object Evaluate()
        {
            if (Parameters.Count < 2)
            {
                throw new ArgumentException(
                    "usage: union(lst1, lst2, ...)");
            }

            List<object> result = new List<object>();

            for (int i = Parameters.Count - 1;
                i >= 0;
                --i)
            {
                List<object> left 
                    = Parameters[i].Evaluate() as List<object>;

                for (int j = i - 1;
                    j >= 0;
                    --j)
                {
                    List<object> right
                        = Parameters[j].Evaluate() as List<object>;
                    foreach (object element in right)
                    {
                        if (left.Contains(element))
                        {
                            result.Add(element);
                        }
                    }
                }
            }

            return result;
        }
    }
}
